var goodsData = require('../../data/goods.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tab:'description',
    goods:[],
    quantity:1,
  },

  changeTab:function(e){
    console.log(e);
    var tab = e.currentTarget.dataset.tab;
    this.setData({tab:tab,});
  },
  //增加商品
  increaseGoods:function(e){
    var quantity = this.data.quantity;
    this.setData({quantity:quantity+1});
  },
  //减少商品
  decreaseGoods:function(e){
    var quantity = this.data.quantity;
    if(this.data.quantity>1) this.setData({quantity:quantity-1});
  },
  //加入购物车
  toCart:function(e){
    console.log(e)
    var id = e.currentTarget.dataset.id;
    var carts = [];
    var cart = new Object();
    let existFlag = false;
    //wx.setStorageSync("carts", []);
    carts = wx.getStorageSync('carts');
    for(var i=0;i<carts.length;i++ ){
      console.log(i);
      if(carts[i].id==id){
        console.log('增加'+id);
        carts[i].quantity = carts[i].quantity+this.data.quantity;
        existFlag = true;
      }
    }
    if(!existFlag){
      cart.id = this.data.goods.id;
      cart.goodsName = this.data.goods.goodsName;
      cart.quantity = this.data.quantity;
      cart.memberPrice = this.data.goods.memberPrice;
      cart.imageUrl = this.data.goods.imageUrl;
      cart.selected = true;
      carts = carts.concat(cart);
    }
    wx.setStorageSync("carts", carts);
    wx.switchTab({
      url: '/pages/shopping/cart/cart',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */

  /* 获得商品数据 */
  getGoodsData:function(id){
    console.log(id);
    let goods;
    let goodsSet = goodsData.goods;
    for(let i in goodsSet){
      let item = goodsSet[i];
      if (item.id==id){
        goods =item;
        break;
      }
    }
    this.setData({
      goods:goods,
    });
  },

  onLoad: function (options) {
    let id = options.id;
    this.getGoodsData(id);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})